package org.huel.backend.service.impl;

import org.huel.backend.domain.dto.StudentScoreDTO;
import org.huel.backend.mapper.StudentScoreMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class StudentScoreService {

    @Autowired
    private StudentScoreMapper studentScoreMapper;

    /**
     * 获取成绩最高的学生列表
     * @param limit 限制返回数量
     * @return 学生成绩数据列表
     */
    public List<StudentScoreDTO> getTopStudentsByScore(int limit) {
        List<StudentScoreDTO> students = studentScoreMapper.findTopStudentsByScore(limit);

        // 计算出勤率
        for (StudentScoreDTO student : students) {
            int total = student.getAttendanceCount() + student.getAbsentCount();
            double rate = total > 0 ? (double) student.getAttendanceCount() / total * 100 : 0;
            student.setAttendanceRate(Math.round(rate * 10) / 10.0); // 保留一位小数
        }

        return students;
    }

    /**
     * 获取出勤统计摘要信息
     */
    public Map<String, Object> getAttendanceSummary() {
        Map<String, Object> summary = studentScoreMapper.getAttendanceSummary();

        // 计算出勤率
        int presentCount = ((Number) summary.get("presentCount")).intValue();
        int absentCount = ((Number) summary.get("absentCount")).intValue();
        int total = presentCount + absentCount;

        double attendanceRate = total > 0 ? (double) presentCount / total * 100 : 0;
        summary.put("attendanceRate", Math.round(attendanceRate * 10) / 10.0);

        // 添加更新时间
        summary.put("lastUpdated", new java.util.Date());

        return summary;
    }
}